package com.bluesmart.mia;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.RequestParams;
import com.sys.Constants;
import com.sys.DemoApp;
import com.util.Constant;
import com.util.ImageLoaderHelper;
import com.util.MgqDataHandler;
import com.util.MgqRestClient;
import com.util.PreferencesUtils;
import com.util.ToastUtil;
import com.util.Utils;
import com.widget.CircleImageView;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.util.FloatMath;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class BabyViewActivity extends FragmentActivity implements OnClickListener,OnTouchListener{
	JSONArray mArray = new JSONArray();
	boolean showWeight = true;

	int chartHeight = 0;
	int addHeight = 0;
	
	Context mContext;
	int mSelected = 0;
	
//	BabyProfileEditActivity babyEdit;
//	BabyCaregiversActivity caregiver;
//	BabyProfileActivity profile;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_baby_view);
	
		((TextView) findViewById(R.id.center)).setText(getString(R.string.baby_profile));
		((Button) findViewById(R.id.right))
				.setCompoundDrawablesWithIntrinsicBounds(0, 0,
						R.drawable.a28, 0);
		((Button) findViewById(R.id.left))
		.setCompoundDrawablesWithIntrinsicBounds(0, 0,
				R.drawable.baby_add, 0);
		
		findViewById(R.id.left).setOnClickListener(this);
		findViewById(R.id.right).setOnClickListener(this);
		findViewById(R.id.btn0).setOnClickListener(this);
		findViewById(R.id.btn1).setOnClickListener(this);
		findViewById(R.id.btn2).setOnClickListener(this);
		
		mContext = this;
		initView();
		
		mSelected = R.id.btn0;
		
		((Button)findViewById(R.id.btn0)).setTextColor(Color.parseColor("#435794"));
		
		FragmentManager fm = getFragmentManager();  
        FragmentTransaction transaction = fm.beginTransaction();  
        transaction.replace(R.id.id_fragment_content, new BabyProfileEditActivity());  
        transaction.commit();  
        
        findViewById(R.id.text0).setOnTouchListener(this);
        findViewById(R.id.text1).setOnTouchListener(this);
        findViewById(R.id.btn0).setOnTouchListener(this);
        findViewById(R.id.btn1).setOnTouchListener(this);
        findViewById(R.id.btn2).setOnTouchListener(this);
	}
	
	float pointY = 0;
	boolean onTap = false;
	@Override
	public boolean onTouch(View arg0, MotionEvent arg1) {
		if(arg1.getAction() == MotionEvent.ACTION_DOWN)
		{
			onTap = false;
			pointY = arg1.getY();
		}
		else if(arg1.getY() - pointY > 40 && !onTap)
		{
			onTap = true;
			findViewById(R.id.icon_layout).setVisibility(View.VISIBLE);
			return true;
		}
		else if(arg1.getY() - pointY < -40 && !onTap)
		{
			onTap = true;
			findViewById(R.id.icon_layout).setVisibility(View.GONE);
			return true;
		}

		return arg0.onTouchEvent(arg1);
	}
	
    public void initView()  {
        findViewById(R.id.layout).setOnTouchListener(new OnTouchListener(){
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				

				if(arg1.getAction() == MotionEvent.ACTION_DOWN)
				{
					pointX = arg1.getX();
					onTap = false;
					pointY = arg1.getY();
				}
				else if(arg1.getAction() == MotionEvent.ACTION_UP)
				{
					if (arg1.getX() - pointX < -40) {
						JSONArray babyList = ((DemoApp)mContext.getApplicationContext()).mBabyList;
						if(((DemoApp)mContext.getApplicationContext()).mSelectedBaby < babyList.size() - 1) 
							((DemoApp)mContext.getApplicationContext()).mSelectedBaby++;
						
						sendSwitchHttpRequest();
						return true;
					} else if (arg1.getX() - pointX > 40) {
						if(((DemoApp)mContext.getApplicationContext()).mSelectedBaby > 0) 
							((DemoApp)mContext.getApplicationContext()).mSelectedBaby--;

						sendSwitchHttpRequest();
						return true;
					}
				}
				else if(arg1.getY() - pointY > 40 && !onTap)
				{
					onTap = true;
					findViewById(R.id.icon_layout).setVisibility(View.VISIBLE);
					return true;
				}
				else if(arg1.getY() - pointY < -40 && !onTap)
				{
					onTap = true;
					findViewById(R.id.icon_layout).setVisibility(View.GONE);
					return true;
				}
				
				return true;
			}
        });
        
        findViewById(R.id.icon_center).setOnTouchListener(new OnTouchListener(){
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				

				if(arg1.getAction() == MotionEvent.ACTION_DOWN)
				{
					pointX = arg1.getX();
				}
				else if(arg1.getAction() == MotionEvent.ACTION_UP)
				{
					if (arg1.getX() - pointX < -40) {
						JSONArray babyList = ((DemoApp)mContext.getApplicationContext()).mBabyList;
						if(((DemoApp)mContext.getApplicationContext()).mSelectedBaby < babyList.size() - 1) 
							((DemoApp)mContext.getApplicationContext()).mSelectedBaby++;
						
						sendSwitchHttpRequest();
						return true;
					} else if (arg1.getX() - pointX > 40) {
						if(((DemoApp)mContext.getApplicationContext()).mSelectedBaby > 0) 
							((DemoApp)mContext.getApplicationContext()).mSelectedBaby--;

						sendSwitchHttpRequest();
						return true;
					}
					else if(Math.abs(arg1.getX() - pointX) < 5)
					{
						showImagePicker();
					}
				}
				
				return true;
			}
        });
        
        setBabyImg();
	}
    
    float pointX = 0;
    float oldDist;
    @SuppressLint("FloatMath")
	private float spacing(MotionEvent event) {
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);
        return FloatMath.sqrt(x * x + y * y);
    }
	
    void setFragment(int viewId)
    {
    	mSelected = viewId;
    	FragmentManager fm = getFragmentManager();  
        // 开启Fragment事务  
        FragmentTransaction transaction = fm.beginTransaction();  

        switch (viewId)  
        {  
        case R.id.btn0:  
            transaction.replace(R.id.id_fragment_content, new BabyProfileEditActivity());  
            break;  
            
        case R.id.btn1:  
            transaction.replace(R.id.id_fragment_content, new BabyProfileActivity()); 
            break;  
            
        case R.id.btn2:  
        	transaction.replace(R.id.id_fragment_content, new BabyCaregiversActivity()); 
        	break;  
        }  
        transaction.commit();  
    }
    
	@Override
	public void onClick(View arg0) {
		if(R.id.btn0 == arg0.getId() || R.id.btn1 == arg0.getId() || R.id.btn2 == arg0.getId())
		{
			((Button)findViewById(R.id.btn0)).setTextColor(Color.WHITE);
			((Button)findViewById(R.id.btn1)).setTextColor(Color.WHITE);
			((Button)findViewById(R.id.btn2)).setTextColor(Color.WHITE);
			((Button)arg0).setTextColor(Color.parseColor("#0D80D6"));
			
			setFragment(arg0.getId());
	        return;
		}
		
		switch(arg0.getId())
		{
		case R.id.icon_center:
			showImagePicker();
			break;
			
		case R.id.right:
			finish();
			break;
			
		case R.id.left:
			startActivity(new Intent(this,AddDeviceActivity.class));
			break;
		}
	}

	void setBabyImg()
	{
		JSONArray babyList = ((DemoApp)mContext.getApplicationContext()).mBabyList;
		int select = ((DemoApp)mContext.getApplicationContext()).mSelectedBaby;
		
		if(babyList != null)
		{
			((TextView)findViewById(R.id.text0)).setText(babyList.getJSONObject(select).getString("babyname"));
			((TextView)findViewById(R.id.text1)).setText(babyList.getJSONObject(select).getString("bday"));
			
			if(select > 0)
			{
				findViewById(R.id.icon_left).setVisibility(View.VISIBLE);
				ImageLoaderHelper.displayImage(R.drawable.a53, (CircleImageView)findViewById(R.id.icon_left), 
						((DemoApp)mContext.getApplicationContext()).mBabyList.getJSONObject(select - 1).getString("image"));
			}
			else
			{
				findViewById(R.id.icon_left).setVisibility(View.INVISIBLE);
			}
			
			if(select < babyList.size() - 1)
			{
				findViewById(R.id.icon_right).setVisibility(View.VISIBLE);
				ImageLoaderHelper.displayImage(R.drawable.a53, (CircleImageView)findViewById(R.id.icon_right), 
						((DemoApp)mContext.getApplicationContext()).mBabyList.getJSONObject(select + 1).getString("image"));
			}
			else
			{
				findViewById(R.id.icon_right).setVisibility(View.INVISIBLE);
			}

			ImageLoaderHelper.displayImage(R.drawable.a53, (CircleImageView)findViewById(R.id.icon_center), 
					((DemoApp)mContext.getApplicationContext()).mBabyList.getJSONObject(select).getString("image"));
		}
	}
	
	public void sendSwitchHttpRequest() {
		MgqDataHandler loginHandler = new MgqDataHandler(mContext, true, false) {
			@Override
			public void onSuccess(String response) {
				setBabyImg();
				
				List<Activity> list = ((DemoApp) getApplicationContext()).getActivityList();
				for(int i = 0; i < list.size(); i++)
				{
					if(list.get(i).getClass().getName().contains("NoteViewActivity"))
					{
						((NoteViewActivity)list.get(i)).sendChartHttpRequest(true);
						break;
					}
				}
				
//				((MainNoticeActivity)list.get(list.size() - 1)).sendAdvRequest();
				
				setFragment(mSelected);
			}
		};
		
		JSONObject obj = ((DemoApp)mContext.getApplicationContext()).getSeletedBaby();

		JSONObject params = new JSONObject();
		params.put("mia_un", PreferencesUtils.getString(mContext, "username"));
		params.put("pwd", PreferencesUtils.getString(mContext, "password"));
		params.put("switchBabyid", obj.getString("babyid"));
		params.put("handType", "switch");
	
		MgqRestClient.postBody(Constant.SERVER_URL + "/sw/babyInfoHandler.ashx", JSON.toJSONString(params), loginHandler);
	}
	
	void showImagePicker()
	{
		final Dialog mDialog = new Dialog(mContext, R.style.Dialog_Fullscreen);
		
		OnClickListener listen = new OnClickListener()
		{
			@Override
			public void onClick(View arg0) {
				if(arg0.getId() == R.id.cancel) mDialog.dismiss();
				else if(arg0.getId() == R.id.pic)
				{
					mDialog.dismiss();
					Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
					getAlbum.setType("image/*");
					startActivityForResult(getAlbum, 3);
				}
				else
				{
					mDialog.dismiss();
					startActivityForResult(new Intent("android.media.action.IMAGE_CAPTURE"), 4);
				}
			}
		};

		mDialog.setContentView(R.layout.dialog_img_choose);
		mDialog.findViewById(R.id.camera).setOnClickListener(listen);
		mDialog.findViewById(R.id.pic).setOnClickListener(listen);
		mDialog.findViewById(R.id.cancel).setOnClickListener(listen);
		mDialog.show();
	}

	private File mPhotoFile;
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (data == null)
			return;
		
		Bitmap bitmap = null;
		if (resultCode == Activity.RESULT_OK) {
			if (requestCode == 4) {
				Uri uri = data.getData();
				if (uri != null) {
					bitmap = BitmapFactory.decodeFile(uri.getPath());
				}

				if (bitmap == null) {
					Bundle bundle = data.getExtras();
					if (bundle != null) {
						bitmap = (Bitmap) bundle.get("data");
					}
				}
			} else if (requestCode == 3) {
				Uri uri = data.getData();
				String[] proj = { MediaStore.Images.Media.DATA };
				Cursor cursor = managedQuery(uri, proj, null, null, null);
				int column_index = cursor
						.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				cursor.moveToFirst();
				bitmap = Utils
						.getImageThumbnail(cursor.getString(column_index));
			}

			if (bitmap == null)
				return;
			
			mPhotoFile = new File(Constants.PIC_PATH);// 将要保存图片的路径
			mPhotoFile.deleteOnExit();
			try {
				BufferedOutputStream bos = new BufferedOutputStream(
						new FileOutputStream(mPhotoFile));
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
				bos.flush();
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

			sendHttpImgRequest(bitmap);
		}
	}
	
	private void sendHttpImgRequest(final Bitmap bitmap) {
		MgqDataHandler loginHandler = new MgqDataHandler(mContext, true, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);

				if (ruser.getString("resCode").equals("1000")) {
					((DemoApp)mContext.getApplicationContext()).sendGetBabyRequest(mContext);
					((ImageView) findViewById(R.id.icon_center)).setImageBitmap(bitmap);
					ToastUtil.showToastWithAlertPic(R.string.success);
				}
				else if (ruser.getString("resCode").equals("2000")) {
					ToastUtil.showToastWithAlertPic(R.string.error_2000);
				}
				else if (ruser.getString("resCode").equals("3000")) {
					ToastUtil.showToastWithAlertPic(R.string.error_3000);
				}
				else
				{
				}
			}
		};
		
		RequestParams params = new RequestParams();
		params.put("mia_un", PreferencesUtils.getString(mContext, "username"));
		params.put("pwd", PreferencesUtils.getString(mContext, "password"));
		params.put("babyid", ((DemoApp)mContext.getApplicationContext()).getSeletedBaby().getString("babyid"));
		try {
			params.put("filename", mPhotoFile);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		MgqRestClient.post(Constant.SERVER_URL + "/sw/uploadimg.ashx", params, loginHandler);
	}
}
